package com.moo2u2.android.oaktononthego.server;

import java.io.IOException;
import java.io.StringWriter;
import java.util.Collection;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.google.gson.JsonObject;

public class Colleagues extends CachedServlet {

    private static final Logger log = Logger.getLogger(Colleagues.class
            .getName());

    /**
     * 
     */
    private static final long serialVersionUID = -639730604809125772L;

    @Override
    @SuppressWarnings("unchecked")
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        log.info("Getting Colleagues");

        PersistenceManager pm = PMF.get().getPersistenceManager();

        try {
            Query q = pm.newQuery(Colleague.class);
            Collection<Colleague> colleagues = (Collection<Colleague>) q.execute();

            Document d = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder().newDocument();
            Element r = d.createElement("colleagues");
            d.appendChild(r);
            for (Colleague colleague : colleagues) {
                r.appendChild(colleague.toXmlNode(d));
            }
            d.normalizeDocument();

            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");

            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(d);
            trans.transform(source, result);
            String xmlString = sw.toString();
            resp.getWriter().print(xmlString);
            q.closeAll();
        } catch (TransformerException e) {
            log.severe("Error transforming xml " + e);
        } catch (ParserConfigurationException e) {
            log.severe("Error creating xml document " + e);
        }
        // catch (Exception e) {
        // JsonObject error = new JsonObject();
        // error.addProperty("success", false);
        // error.addProperty("errorMsg", e.getMessage());
        // error.addProperty("error", e.toString());
        // resp.getWriter().print(error.toString());
        // log.severe("Error writing xml " + e);
        // }
        finally {
            pm.close();
            resp.getWriter().flush();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        log.info("Adding fake Colleagues");

        PersistenceManager pm = PMF.get().getPersistenceManager();

        try {
            Colleague proxy = new Colleague();
            proxy.setName("Jason Woods");
            proxy.setSnippet("GE Money, 234 George St, Sydney 2000\n\nPh: +61 409 047 103");
            proxy.setLongitude((int) (151.207213 * 1E6));
            proxy.setLatitude((int) (-33.863696 * 1E6));
            proxy.setImg("jason.png");
            pm.makePersistent(proxy);

            proxy = new Colleague();
            proxy.setName("Sam Bradon");
            proxy.setSnippet("Oakton, 65 Berry St, North Sydney\n\nPh: +61 411 653725");
            proxy.setLongitude((int) (151.207902 * 1E6));
            proxy.setLatitude((int) (-33.837106 * 1E6));
            proxy.setImg("sam.png");
            pm.makePersistent(proxy);

            proxy = new Colleague();
            proxy.setName("James Donohoe");
            proxy.setSnippet("ING, 140 Sussex St, Sydney 2000 \n\nPh: +61 448 801 717");
            proxy.setLongitude((int) (151.203549 * 1E6));
            proxy.setLatitude((int) (-33.869605 * 1E6));
            proxy.setImg("james.png");
            pm.makePersistent(proxy);

            resp.getWriter().write("Success");
        } catch (Exception e) {
            JsonObject error = new JsonObject();
            error.addProperty("success", false);
            error.addProperty("error", e.getMessage());
            resp.getWriter().print(error.toString());
        } finally {
            pm.close();
            resp.getWriter().flush();
        }
    }
}
